/*
============================================================================
 Name        : nmsJpegUtil.c
 Author      : Jian
 Version     :
 Copyright   : base on http://ce.sharif.edu/~ahmadinejad/jpeg/
 Description : nmsJpegUtil.c - source file
============================================================================
*/

/* INCLUDE FILES */
#include "nmsJpegUtil.h"

const UINT8 _zigZagScanner[64] = {
    0,  1,  8, 16,  9,  2,  3, 10,
    17, 24, 32, 25, 18, 11, 4, 5,
    12, 19, 26, 33, 40, 48, 41, 34,
    27, 20, 13, 6,  7, 14, 21, 28,
    35, 42, 49, 56, 57, 50, 43, 36,
    29, 22, 15, 23, 30, 37, 44, 51,
    58, 59, 52, 45, 38, 31, 39, 46,
    53, 60, 61, 54, 47, 55, 62, 63
} ;


int nmsJpegReadFile(HFILE file, void* data, int len)
{
    int readed = 0 ;

    __NMS_ASSERT_DEFENSE(len > 0, return -1) ;

    nmsFsRead(file, data, len, &readed) ;

    if (readed == 0) {
        nprintf("_readFile error or reach the end of file") ;
        return -1 ;
    }

    return readed ;
}

int nmsJpegRead2ByteBigEndian(HFILE file)
{
    UINT16 byte2 = 0 ;
    nmsJpegReadFile(file, &byte2, 2) ;
    return __COVERT_2BYTE_ENDIAN(byte2) ;
}

void nmsJpegFromZigZag4(int* data)
{
    int tmp[64] = {0} ;
    int i = 0 ;
    for (; i < 64; i++)
        tmp[_zigZagScanner[i]] = data[i] ;

    memcpy(data, tmp, 64 * sizeof(int)) ;
}

void nmsJpegToZiZag(int* data)
{
    int tmp[64] = {0} ;
    int i = 0 ;
    for (; i < 64; i++)
        tmp[i] = data[_zigZagScanner[i]] ;

    memcpy(data, tmp, 64 * sizeof(int)) ;
}

void nmsJpegToZiZag1(UINT8* data)
{
    UINT8 tmp[64] = {0} ;
    int i = 0 ;
    for (; i < 64; i++)
        tmp[i] = data[_zigZagScanner[i]] ;

    memcpy(data, tmp, 64 * sizeof(UINT8)) ;
}

UINT32 nmsJpegGetRgb(nmsRgbMatrix* matrix, UINT32 x, UINT32 y)
{
    int mX = x ;
    int mY = y ;
    int m  = 0 ;

    __NMS_ASSERT_DEFENSE(x < 16 && y < 16, return 0) ;

    if (y >= 8) {
        m += 2 ;
        mY -= 8 ;
    }

    if (x >= 8) {
        m += 1 ;
        mX -= 8 ;
    }

    return (*matrix)[m][mX + mY * 8] ;
}

/* End of File */
